<?php
/**
 * Handles the jabberdrive distributed-file-system feature 
 * 
 * @author Gustav Knutsson
 */
class jdDFS{
	// Holds the jabberdrivenetworkmeta object
	public $jdnm;
	
	// Holds the jddbmysql object.
	public $jddb;
	
	/**
	 * Class construct
	 * @author Gustav Knutsson
	 */
	public function __construct(){
		$this->jdnm = new jdNetworkMeta();
		$this->jddb = jdDatabaseMySql::getInstance();
	}
	
	/**
	 * 
	 * @param INT $node_id
	 * @param String $filename
	 * @param String $filedata
	 * @return bool success
	 */
	public function SaveToNode($node_id, $filename, $filedata){
		$node = $this->_getNode($node_id);
		
		//set POST variables
		$fields = array(
			'jbbdath' => $node[0]['n_auth_string'],
			'file1_data'=> urlencode($filedata),
			'file1_name'=> $filename
		);
		
		$msg = new jdNetworkMessage;
		$msg->setRecipient($node[0]['n_address']."insert.php");
		$msg->_send($fields);
		
		if(trim($msg->_answer()) == 'jdnfs:ok'){// Check that we get the jdnfs:ok (Jabberdrive Node File Save)
			print 'OK';
			return true;
		}else{
			print 'NOK';
			return false;
		}
	}
	
	/**
	 * Saves a new file, received from ethernet node.
	 * @return String
	 */
	public function SaveFromNode($authstring, $filename, $filedata){
		if($this->_getThisAuthString() == urldecode($authstring)){
			$jds = new jdStorage();
			$jds->NodeStore($filedata, $filename);
			
			print 'jdnfs:ok';
		}else{
			die("<b>jdError:</b> Authentication failed.");
		}
	}
	
	/**
	 * Returns THIS nodes authstring.
	 * @return String
	 * 
	 * @author Gustav Knutsson
	 */
	private function _getThisAuthString(){
		$r = $this->jddb->fetch("SELECT cc_value FROM core_configuration WHERE cc_variable = 'NODE_AUTHSTRING'");
		return $r[0]['cc_value'];
	}
	
	/**
	 * Returns info about a special node
	 * 
	 * @param INT $n_id
	 * @return Array
	 * 
	 * @author Gustav Knutsson
	 */
	private function _getNode($n_id){
		return $this->jddb->fetch("SELECT * FROM nodes WHERE n_id = '".$n_id."' LIMIT 1");
	}
}
?>